package top.csy8888.deadqueue.service;

import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Service;
import top.csy8888.deadqueue.consts.RabbitConstants;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author CSY
 * @date 2025 - 10 - 16
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ConsumerService {
    private final RedisTemplate<String,Integer> redisTemplate;

    @RabbitListener(queues = RabbitConstants.QUEUE_NAME)
    public void receive(String message, Channel channel, @Headers Map<String,Object> headers) {
        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try{
            int i = 10 / 0;
            log.info(String.valueOf(i));
            channel.basicAck(tag,false);
        }catch (Exception e){
            boolean flag = true;
            if (Boolean.FALSE.equals(redisTemplate.hasKey("retry"))) {
                redisTemplate.opsForValue().set("retry",0,30, TimeUnit.MINUTES);
            }
            if (redisTemplate.opsForValue().increment("retry") > 3){
                redisTemplate.delete("retry");
                flag = false;
            }
            log.info("错误");
            try {
                channel.basicReject(tag,flag);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
